package com.kdtech.analyse.Bbs;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.NumberUtils;
import com.kdtech.utils.StringUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.kdtech.analyse.AnalyseNews;
import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;

public class BtsmthBbsAnalyse implements AnalyseNews{

	
	public boolean isDetailPage(String url){
		boolean bRet = false;
		String[] regex = {
			"http://www.btsmth.com/show_topic.php\\?en_name=[a-zA-Z]*&gid=[0-9]*",
		};
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta bbs = new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt = urlMeta.getHtml();
		String url = urlMeta.getUrl();
		if(!isDetailPage(url)){
		}
		bbs.setUrl(url);
		String title = null;
		String content = null;
		String author = null;
		Long date = null;
		Integer clickNum=0;
		Integer commentNum=0;

		Document doc = Jsoup.parse(htmltxt);
		title =doc.select("h2").text();
		date = DateUtils.matchDate(doc.select("td[width=200]").html());
		content = StringUtils.substringBetween(htmltxt, "print_block(2,", " true);");
		
		Elements authorList = doc.select("div.rp_z_rt p span");
//		System.err.println(authorList);
		
		if(authorList.size()>0)
		{
			author = authorList.get(0).text();
		}
		
		bbs.setClickNum(clickNum);
		bbs.setCommentNum(commentNum);
		bbs.setTitle(StringUtils.trimSpace(title));
		bbs.setContent(content);
		bbs.setAuthor(author);
		bbs.setDate(date);
		bbs.setUpdateUrl(url);
		return bbs;
	}
	
	public NewsMeta Update(NewsMeta meta) {
		String url = meta.getUpdateUrl();
		if (StringUtils.isNotBlank(url)){
			UrlMeta urlMeta = CrawlHTML.responseToURL(url);
			return parserHtml(urlMeta);
		}
		return null;
	}
    
	
}
